package com.cnhis.cloudhealth.clinical.medical.base.bo;


import com.cnhis.cloudhealth.clinical.medical.base.dao.MperformDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.cardmember.bo.CardMemberMangerBo;
import com.cnhis.cloudhealth.commons.commonSql.bo.CommonSqlBo;
import com.cnhis.cloudhealth.commons.newid.GetNewId;
import com.cnhis.cloudhealth.commons.utils.DateUtils;
import com.cnhis.cloudhealth.commons.utils.GlobalVariable;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
import com.cnhis.cloudhealth.commons.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class MperformBo {
    @Resource
    private MperformDao mperformDao;
    @Autowired
    private GetNewId getNewId;

    @Autowired
    private CardMemberMangerBo cardMemberMangerBo;

    @Autowired
    private CommonSqlBo commonSqlBo;

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(修改附属医嘱费用明细状态)Techic_VBJ_Insert
     * @author chengshaowei
     * @date 2016/9/19 10:30
     */
    public Map<String, Object> costDetail(Map<String, Object> map) throws Exception {
        Map<String, Object> msg = new HashMap<String, Object>();
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
        Integer ACF01 = GlobalVariable.IntegerIsNull(map.get("acf01"));
        for (Map<String, Object> m : list) {
            String vbi13 = "";//执行状态
            Long VBI01 = GlobalVariable.LongIsNull(m.get("vbi01"));//医嘱抄送id;
            Long VAF01 = GlobalVariable.LongIsNull(m.get("vaf01"));//医嘱ID
            Long VBI03 = GlobalVariable.LongIsNull(m.get("vbi03"));//抄送号
            if (VBI01 == 0l) {
                msg.put("falg", false);
                msg.put("msg", "操作失败，医嘱抄送记录不存在{医嘱：" + VAF01 + " 抄送号:" + VBI03 + "}");
                return msg;
            }
            Integer VBJ05 = GlobalVariable.IntegerIsNull(m.get("vbj05"));//本次次数
            Integer VBI35 = GlobalVariable.IntegerIsNull(m.get("vbi35"));//剩余次数
            if (VBJ05 > VBI35) {
                msg.put("falg", false);
                msg.put("msg", "操作失败，医嘱本次执行数量大于剩余执行数量{医嘱：" + VAF01 + " 抄送号:" + VBI03 + "}");
                return msg;
            }
            /**获取医嘱抄送记录**/
            if (ACF01 == 1) {
                Map<String, Object> vbi1 = mperformDao.findByVBI1(m);
                if (vbi1 != null) {
                    vbi13 = GlobalVariable.StringIsNull(vbi1.get("vbi13"));
                } else {
                    Map<String, Object> vbi1_2 = mperformDao.findByVBI1_2(m);
                    if (vbi1_2 != null) {
                        vbi13 = GlobalVariable.StringIsNull(vbi1_2.get("vbi13"));
                    }
                }
                if ("".equals(vbi13)) {
                    msg.put("falg", false);
                    msg.put("msg", "医嘱已执行完成.");
                    return msg;
                }
                /**对应遗嘱是否发送**/
                Map<String, Object> vaf1 = mperformDao.findByVAF1(m);
                if (vaf1 != null) {
                    msg.put("falg", false);
                    msg.put("msg", "对应医嘱还没发送，不能执行.");
                    return msg;
                }
                /**项目是否收费**/
                List<Map<String, Object>> vaj1 = mperformDao.findVAJ1(m);
                if (vaj1 != null && vaj1.size() > 0) {
                    msg.put("falg", false);
                    msg.put("msg", "此项目还未收费，请刷卡扣费或到收费室缴费.");
                    return msg;
                }
                /**赋值**/
                m.put("vaa01", map.get("vaa01"));
                m.put("vbj01", getNewId.nextId());
                m.put("vbj08", new Date());
                m.put("vbj10", new Date());
                m.put("bce03b", map.get("bce03"));
                m.put("vaa07", map.get("vaa07"));
                /**剩余次数减去本次次数**/
                Integer new_VBI35 = VBI35 - VBJ05;
                m.put("vbi35", new_VBI35);
                if (new_VBI35 == 0) {
                    m.put("vbi13", 1);
                } else {
                    m.put("vbi13", 3);
                }
                Map<String, Object> vaib = mperformDao.findTmpVAIb(m);
                Map<String, Object> vaa1 = mperformDao.findMembers(m);
                Integer RateMode = GlobalVariable.IntegerIsNull(map.get("RateMode"));
                if (RateMode > 0 && vaib != null && vaa1 != null) {
                    msg.put("falg", false);
                    msg.put("msg", "病人不是会员，请先到收费处交钱");
                    return msg;
                }
                /**未扣费判断**/
                Map<String, Object> deduction = mperformDao.findByDeduction(m);
                if (deduction != null) {
                    msg.put("falg", false);
                    msg.put("msg", "执行安排操作失败,还未扣费，不能执行");
                    return msg;
                }
                /**修改抄嘱状态**/
//                List<Map<String, Object>> copystate = mperformDao.findCopyState(m);
//                if (copystate != null && copystate.size() > 0) {
                    //查询是否有子医嘱
//                    Map<String, Object> np = new HashMap<String, Object>();
//                    np.put("vaf01", VAF01);
//                    List<Map<String, Object>> slist = mperformDao.findVbi1ByVaf1Sid(np);
//                    if (slist != null && slist.size() > 0) {
//                        m.put("list", slist);
//                        mperformDao.batchUpdateVbi1(m);
//                        mperformDao.batchUpdateVbi1_2(m);
//                    }
                    mperformDao.updateVbi1(m);
                    mperformDao.updateVbi1_2(m);
//                }
                mperformDao.costDetail1(m);
                mperformDao.costDetail1_2(m);
            } else {
                /**赋值**/
                m.put("vaa01", map.get("vaa01"));
                m.put("vbj01", getNewId.nextId());
                m.put("vbj08", new Date());
                m.put("vbj10", new Date());
                m.put("bce03b", map.get("bce03"));
                m.put("vaa07", map.get("vaa07"));
                Map<String, Object> vbi2 = mperformDao.findByVBI2(m);
                if (vbi2 != null) {
                    vbi13 = GlobalVariable.StringIsNull(vbi2.get("vbi13"));
                }
                if ("".equals(vbi13)) {
                    msg.put("falg", false);
                    msg.put("msg", "医嘱已执行完成.");
                    return msg;
                }
                /**剩余次数减去本次次数**/
                Integer new_VBI35 = VBI35 - VBJ05;
                m.put("vbi35", new_VBI35);
                if (new_VBI35 == 0) {
                    m.put("vbi13", 1);
                } else {
                    m.put("vbi13", 3);
                }
                /**对应遗嘱是否发送**/
                Map<String, Object> vaf2 = mperformDao.findByVAF2(m);
                if (vaf2 != null) {
                    msg.put("falg", false);
                    msg.put("msg", "对应医嘱还没发送，不能执行.");
                    return msg;
                }
                mperformDao.updateVbi2(m);
                if (StringUtils.isEmpty(m.get("vbi05").toString())) {
                    m.put("vbi05", 0);
                }
                mperformDao.costDetail2(m);
            }
        }
        /**批量保存医嘱记录**/
        mperformDao.batchinsertByVo(list);
        msg.put("falg", true);
        msg.put("msg", "执行完成");
        return msg;
    }

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(一卡通扣费)
     * @author chengshaowei
     * @date 2016/10/24 13:26
     */
    public Map<String, Object> deduction(Map<String, Object> map) throws Exception {
        Map<String, Object> msg = new HashMap<String, Object>();
        BigDecimal revaj38 = new BigDecimal(0);
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
        Integer ACF01 = GlobalVariable.IntegerIsNull(map.get("acf01"));
        ModelVo mv = new ModelVo();
        mv = Techic_VBJ_Insert_Pretreat(list, map, revaj38);
        if (StaticKeys.OH_FALSE.equals(mv.getResult())) {
            msg.put("falg", false);
            msg.put("msg", mv.getResultMsg());
            return msg;
        }
        revaj38 = GlobalVariable.BigDecimalNull(mv.getMap().get("revaj38"));
        List<Map<String, Object>> pmlist = (List<Map<String, Object>>) mv.getMap().get("list");
        mv = HORate_Card_Balance(map, revaj38);
        if (StaticKeys.OH_FALSE.equals(mv.getResult())) {
            msg.put("falg", false);
            msg.put("msg", mv.getResultMsg());
            return msg;
        }
        for (Map<String, Object> pm : pmlist) {
            Map<String, Object> cardMap = new HashMap<String, Object>();
            cardMap.put("VAA01", GlobalVariable.LongIsNull(map.get("vaa01")));//病人ID
            cardMap.put("VAA07", GlobalVariable.LongIsNull(map.get("vaa07")));//就诊ID
            cardMap.put("VAI01", GlobalVariable.LongIsNull(pm.get("vai01")));//单据ID,如果传入当前记账ID为记账状态，则不再扣费
            cardMap.put("ACF01", ACF01);//服务对象 1=门诊、2=住院
            cardMap.put("BCE01", map.get("BCE01"));//操作员id
            cardMap.put("BCK01", map.get("BCK01"));//科室id
            cardMap.put("BCE02", map.get("BCE02"));//操作员code
            cardMap.put("BCE03", map.get("bce03"));//操作员姓名
            cardMap.put("VAJ38", pm.get("vai23"));//基本账户扣费
            cardMap.put("AType", 0);//0 = 扣费,1 = 退费
            cardMap.put("AWorkType", 4);//1=门诊记账，2=药房发药，3=医嘱记账，4=医技执行,5=挂号，6=门诊结账 , 7=住院结帐,8=简易挂号
            mv = cardMemberMangerBo.updatehoratecardcharge(cardMap);
            if (StaticKeys.OH_FALSE.equals(mv.getResult())) {
                msg.put("falg", false);
                msg.put("msg", mv.getResultMsg());
                return msg;
            }
        }
        msg.put("falg", true);
        msg.put("msg", "执行完成");
        return msg;
    }

    /**
     * @param '[list]'
     * @return void
     * @throws
     * @Description:(医技执行记录)
     * @author chengshaowei
     * @date 2016/10/24 8:49
     */
    public ModelVo Techic_VBJ_Insert_Pretreat(List<Map<String, Object>> list,
                                              Map<String, Object> map, BigDecimal revaj38) throws Exception {
        Map<String, Object> pamap = new HashMap<String, Object>();
        pamap.put("list", list);
        ModelVo mv = new ModelVo();
        List<Map<String, Object>> palist = mperformDao.findByPretreatAdvice(pamap);
        for (Map<String, Object> m : palist) {
            Integer VAF10 = GlobalVariable.IntegerIsNull(m.get("vaf10"));
            Integer VAF11 = GlobalVariable.IntegerIsNull(m.get("vaf11"));
            if (Arrays.asList(1, 2, 4).contains(VAF10) && VAF11 == 2) {
                mv.setResult(StaticKeys.OH_FALSE);
                mv.setResultMsg("对应医嘱还没发送，不能执行.");
                return mv;
            }
        }
        List<Map<String, Object>> pmlist = mperformDao.findByPretreatMoney(palist);
        String ReVAIid = "";
        for (Map<String, Object> m : pmlist) {
            BigDecimal VAI23 = GlobalVariable.BigDecimalNull(m.get("vai23"));
            String VAI01 = GlobalVariable.StringIsNull(m.get("vai01"));
            revaj38 = revaj38.add(VAI23);
            ReVAIid = ("".equals(ReVAIid) ? "" : (ReVAIid + ",")) + VAI01;
        }
        mv.setResult(StaticKeys.OH_SUCCESS);
        mv.setResultMsg("计算结账金额成功.");
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("revaj38", revaj38);
        returnMap.put("list", pmlist);
        mv.setMap(returnMap);
        return mv;
    }

    /**
     * @param '[list]'
     * @return void
     * @throws
     * @Description:(检索卡余额)
     * @author chengshaowei
     * @date 2016/10/24 8:49
     */
    public ModelVo HORate_Card_Balance(Map<String, Object> map, BigDecimal revaj38) throws Exception {
        ModelVo mv = new ModelVo();
        Map<String, Object> cardBalance = mperformDao.findByCardBalance(map);
        if (cardBalance != null) {
            BigDecimal VBU14 = GlobalVariable.BigDecimalNull(cardBalance.get("vbu14"));
            BigDecimal BEP06B = GlobalVariable.BigDecimalNull(cardBalance.get("bep06b"));
            if (VBU14.add(BEP06B).compareTo(revaj38) == -1) {
                mv.setResult(StaticKeys.OH_SUCCESS);
                mv.setResultMsg("余额不足.");
                return mv;
            }
        }
        mv.setResult(StaticKeys.OH_SUCCESS);
        mv.setResultMsg("余额大于本次需扣费金额.");
        return mv;
    }

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(医技退费审核确认)
     * @author chengshaowei
     * @date 2016/9/19 10:30
     */
    public Map<String, Object> findRefund(Map map) throws Exception {
        return mperformDao.findRefund(map);
    }

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(更新退费)
     * @author chengshaowei
     * @date 2016/9/19 10:30
     */
    public Map<String, Object> refund(Map<String, Object> map) throws Exception {
        Map<String, Object> msg = new HashMap<String, Object>();
        /**这里需要扣费HORate_CardCharge_Update**/
        for (Map<String, Object> m : (List<Map<String, Object>>) map.get("list")) {
            Map<String, Object> backMap = mperformDao.findAppRefund(m);
            if (backMap != null) {
                msg.put("falg", false);
                msg.put("msg", "费用ID:" + m.get("VAJ01").toString() + "已经审核或拒绝退费，请返回刷新重新提交.");
                return msg;
            } else {
                m.put("BCE01B", map.get("BCE01B"));
                m.put("BCE03B", map.get("BCE03B"));
                m.put("lDate", map.get("lDate"));
                mperformDao.refund1(m);
                mperformDao.refund2(m);
            }
        }
        msg.put("falg", true);
        msg.put("msg", "审核成功");
        return msg;
    }

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(判断是否会员一卡通扣费病人)
     * @author chengshaowei
     * @date 2016/9/19 10:30
     */
    public Map<String, Object> findByVAA1(Map map) throws Exception {
        return mperformDao.findByVAA1(map);
    }

    /**
     * @param '[map]'
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     * @Description:(查询医技申请)
     * @author chengshaowei
     * @date 2016/9/19 10:30
     */
    public Map<String, Object> findByMedicalApp(Map map) throws Exception {
        return mperformDao.findByMedicalApp(map);
    }

    /**
     * @param '[map]'
     * @return void
     * @throws
     * @Description:(取消呼叫)
     * @author chengshaowei
     * @date 2016/10/27 9:49
     */
    public void deleteVCZ1(Map<String, Object> map) throws Exception {
        mperformDao.deleteVCZ1(map);
    }

    /**
     * @param '[map]'
     * @return void
     * @throws
     * @Description:(查询退费申请是否存在)
     * @author chengshaowei
     * @date 2016/10/27 9:49
     */
    public List<Map<String, Object>> findByVBY1(Map<String, Object> map) throws Exception {
        return mperformDao.findByVBY1(map);
    }

    /**
     * @param '[map]'
     * @return void
     * @throws
     * @Description:(给药途径退费申请)
     * @author chengshaowei
     * @date 2016/10/27 9:49
     */
    public List<Map<String, Object>> findDrugWayreFund(Map<String, Object> map) throws Exception {
        return mperformDao.findDrugWayreFund(map);
    }


    /**
     * @param '[map]'
     * @return void
     * @throws
     * @Description:(医技费用记录申请退费)
     * @author chengshaowei
     * @date 2016/10/27 9:49
     */
    public List<Map<String, Object>> findMedicalRefund(Map<String, Object> map) throws Exception {
        return mperformDao.findMedicalRefund(map);
    }


    /**
     * @param '[map]'
     * @return void
     * @throws
     * @Description:(申请退费,药房、医技直接传 审批 状态
     * HORate_VBY1_Data
     * @lMode int    --操作类型 0=申请, 1=审批, 2=拒绝
     * @lBCE01 int    --申请人或审批人
     * @lSource int    --0：医师站 1：药房，2：医技工作站，3：收费 4=门诊输液工作站
     * @BCK01D int=0  --药品退药科室
     * lBCE03   int 操作人
     * )
     * @author chengshaowei
     * @date 2016/10/27 9:49
     */
    public ModelVo horatevby1data(Map<String, Object> map) throws Exception {
        ModelVo vo = new ModelVo();
        Date lDate = new Date();
        String Param = commonSqlBo.getSysParamValue(100, 105002, 160);
        String lBCE03 = GlobalVariable.StringIsNull(map.get("lBCE03"));
        Integer lSource = GlobalVariable.IntegerIsNull(map.get("lSource"));
        Integer lMode = GlobalVariable.IntegerIsNull(map.get("lMode"));
        Integer lVAJ01 = 0;
        if (!"1".equals(Param) && lSource == 0 && lMode == 0) {
            vo.setResult(StaticKeys.OH_FALSE);
            vo.setResultMsg("申请失败");
            return vo;
        }
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
        if (list != null && list.size() > 0) {
            /**当门诊输液工作站申请退费时，判断申请退费项目是否存在**/
            List<Map<String, Object>> vbyList = mperformDao.findVBY1Exists(map);
            if (lSource == 4 && vbyList != null && vbyList.size() > 0) {
                vo.setResult(StaticKeys.OH_FALSE);
                vo.setResultMsg("申请退费项目已经存在，不能重复申请");
                return vo;
            }
            List<Map<String, Object>> tmpVBYyes = mperformDao.tmpVBYyes(map);
            List<Map<String, Object>> tmpVBYno = mperformDao.tmpVBYno(map);
            for (Map<String, Object> m : list) {
                Long m_vaj01 = GlobalVariable.LongIsNull(m.get("vaj01"));
                for (Map<String, Object> yes : tmpVBYyes) {
                    Long yes_vaj01 = GlobalVariable.LongIsNull(yes.get("vaj01"));
                    if (m_vaj01.equals(yes_vaj01)) {
                        //设置vby表
                        //设置vby表
                        yes.put("bce01b", map.get("lBCE01"));
                        yes.put("bce03b", lBCE03);
                        yes.put("vby08", lDate);
                        yes.put("vby10", m.get("remark"));
                        yes.put("vby09", lMode);
                        yes.put("bck01", 0);
                        //-----------------------------------------
                        yes.put("vaj25", m.get("vaj25"));
                        yes.put("remark", m.get("remark"));
                    }
                }
                for (Map<String, Object> no : tmpVBYno) {
                    Long no_vaj01 = GlobalVariable.LongIsNull(no.get("vaj01"));
                    if (m_vaj01.equals(no_vaj01)) {

                        //设置vby表
                        no.put("bce01a", map.get("lBCE01"));
                        no.put("bce03a", lBCE03);
                        no.put("vby04", lDate);
                        no.put("vby05", m.get("remark"));
                        no.put("vby09", lMode);
                        if (lMode >= 1 && lMode <= 2) {
                            no.put("bce01b", map.get("lBCE01"));
                            no.put("bce03b", lBCE03);
                            no.put("vby08", lDate);
                            no.put("vby10", m.get("remark"));
                        } else {
                            no.put("bce01b", 0);
                            no.put("bce03b", "");
                            no.put("vby08", DateUtils.String2Date("1900-01-01 00:00:00"));
                            no.put("vby10", "");
                        }
                        no.put("bck01", 0);
                        //-----------------------------------------
                        no.put("vaj25", m.get("vaj25"));
                        no.put("remark", m.get("remark"));
                    }
                }
            }
            /**请先让医师取消xx医嘱**/
            Map<String, Object> vaj = mperformDao.findVajByVaf01(tmpVBYno);
            if (!"1".equals(Param) && lSource >= 1 && lSource <= 2 && vaj != null) {
                vo.setResult(StaticKeys.OH_FALSE);
                vo.setResultMsg("请先让医师取消 [" + vaj.get("vaf22") + "] 医嘱.");
                return vo;
            }
            for (Map<String, Object> m : list) {
                Map<String, Object> vvajfull = mperformDao.findvvajfull(m);
                if (vvajfull != null) {
                } else {
                    vo.setResult(StaticKeys.OH_FALSE);
                    vo.setResultMsg("费用明细id： [" + m.get("vaj01") + "] 不存在.");
                    return vo;
                }
            }
            //todo insert update
            mperformDao.batchinsertByVby1(tmpVBYno);
            if (lSource >= 1 && lSource <= 2) {
                mperformDao.batchupdateByVby1(tmpVBYyes);
            }
        } else {
            vo.setResult(StaticKeys.OH_FALSE);
            vo.setResultMsg("提交文档错误，信息为空");
            return vo;
        }
        vo.setResult(StaticKeys.OH_SUCCESS);
        vo.setResultMsg("退费申请成功");
        return vo;
    }
}
